using System;
using System.Collections.Generic;
using System.Windows.Forms;
using NLog;

namespace mEdit
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.ThreadException += (sender, args) => Application_ThreadException(sender, args);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new mEditMainForm());
        }

        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs args)
        {
            LogException("[UI thread]", args.Exception);
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            LogException("[Non UI Thread]", e.ExceptionObject as Exception);
        }

        private static void LogException(string type, Exception e)
        {
            ExceptionInfo einfo = new ExceptionInfo();
            einfo.ShowDialog();
            string userinfo = string.Format("userinfo: {0}", einfo.UserProvidedInformation);

            Logger logger = NLog.LogManager.GetCurrentClassLogger();
            string exception_startblock = "---- [ Exception ] ----";
            string exception_endblock = "---- [ End Of Exception Data ] ----";
            string exceptiopnMessage =
                string.Format("InnerException: {1}{0}, Message: {2}{0} Source: {3}{0} Stacktrace: {4}{0} TargetSite: {5}{0}",
                Environment.NewLine,
                e.InnerException != null ? e.InnerException.ToString() : "<none>", 
                e.Message, 
                e.Source, 
                e.StackTrace, 
                e.TargetSite);
            exceptiopnMessage = string.Format("{3}{2}{0}{2}{1}{2}{5}{2}{2}{4}{2}{2}", type, exceptiopnMessage, Environment.NewLine, exception_startblock, exception_endblock, userinfo);
            logger.Log(NLog.LogLevel.Fatal, exceptiopnMessage);

            Application.Exit();
        }

    }
}